import { Request, Response } from 'express';
import { AuthRequest } from '@/types';
import postService from '@/services/system/post.service';
import ApiResponse from '@/utils/api/api-response.util';
import ExcelUtil, { ExcelField } from '@/utils/excel/excel.util';
import { Log, BusinessType } from '@/decorators/Log';
import { RepeatSubmit } from '@/decorators/repeatSubmit.decorator';
import { getLogger } from '@/utils/logger';

// 创建模块专用的日志记录器
const consoleLogger = getLogger("post-controller");
const logger = getLogger("post-controller", {
  console: false,
});

/**
 * 岗位信息控制器
 */
class PostController {
  /**
   * 获取岗位列表
   * @param req 请求对象
   * @param res 响应对象
   */
  async list(req: AuthRequest, res: Response) {
    try {
      // 请求日志
      consoleLogger.info("获取岗位列表请求", {
        query: req.query,
        operator: req.user?.userName || 'unknown',
      });
      
      // 获取分页和查询参数
      const { pageNum, pageSize, ...params } = req.query;
      
      // 查询岗位列表
      const data = await postService.selectPostList(
        params,
        parseInt(pageNum as string) || 1,
        parseInt(pageSize as string) || 10
      );
      
      // 结果日志
      logger.info("获取岗位列表成功", {
        response: {
          total: Array.isArray(data) ? data.length : data.total,
          count: Array.isArray(data) ? data.length : data.rows.length
        },
        operator: req.user?.userName || 'unknown',
      });
      
      ApiResponse.successWithoutWrapper(res, data);
    } catch (error) {
      // 详细的错误日志
      consoleLogger.error(`获取岗位列表失败: ${error instanceof Error ? error.message : String(error)}`, {
        requestData: {
          query: req.query,
        },
        operator: req.user?.userName || 'unknown',
        stack: error instanceof Error ? error.stack : undefined
      });
      if (!res.headersSent) {
        ApiResponse.error(res, '获取岗位列表失败');
      }
    }
  }
  
  /**
   * 导出岗位列表
   * @param req 请求对象
   * @param res 响应对象
   */
  async export(req: AuthRequest, res: Response) {
    try {
      // 请求日志
      consoleLogger.info("导出岗位列表请求", {
        query: req.query,
        operator: req.user?.userName || 'unknown',
      });
      
      // 获取查询参数
      const params = req.query;
      
      // 查询岗位列表（不分页）
      const result = await postService.selectPostList(params);
      
      // 确保获取到的是数组类型
      const data = Array.isArray(result) ? result : result.rows;
      
      // 定义Excel字段配置
      const fields: ExcelField[] = [
        { header: '岗位序号', key: 'postId', width: 10 },
        { header: '岗位编码', key: 'postCode', width: 15 },
        { header: '岗位名称', key: 'postName', width: 20 },
        { header: '岗位排序', key: 'postSort', width: 10 },
        { header: '状态', key: 'status', width: 10, 
          formatter: (value) => value === '0' ? '正常' : '停用' },
        { header: '创建者', key: 'createBy', width: 15 },
        { header: '创建时间', key: 'createTime', width: 20, 
          formatter: (value) => value ? new Date(value).toLocaleString() : '' },
        { header: '备注', key: 'remark', width: 30 }
      ];
      
      // 生成文件名
      const fileName = `岗位数据_${new Date().getTime()}`;
      
      // 导出Excel到响应
      await ExcelUtil.exportToResponse(res, data, fields, fileName, '岗位数据');
      
      // 结果日志
      logger.info("导出岗位列表成功", {
        response: {
          count: data.length
        },
        operator: req.user?.userName || 'unknown',
      });
      
      // 返回值，解决"并非所有代码路径都返回值"的错误
      return;
    } catch (error) {
      // 详细的错误日志
      consoleLogger.error(`导出岗位列表失败: ${error instanceof Error ? error.message : String(error)}`, {
        requestData: {
          query: req.query,
        },
        operator: req.user?.userName || 'unknown',
        stack: error instanceof Error ? error.stack : undefined
      });
      if (!res.headersSent) {
        ApiResponse.error(res, '导出岗位列表失败');
      }
    }
  }
  
  /**
   * 获取岗位选择框列表
   * @param req 请求对象
   * @param res 响应对象
   */
  async optionSelect(req: AuthRequest, res: Response) {
    try {
      // 请求日志
      consoleLogger.info("获取岗位选择框列表请求", {
        operator: req.user?.userName || 'unknown',
      });
      
      // 查询所有岗位
      const data = await postService.selectPostAll();
      
      // 结果日志
      logger.info("获取岗位选择框列表成功", {
        response: {
          count: data.length
        },
        operator: req.user?.userName || 'unknown',
      });
      
      ApiResponse.success(res, data);
    } catch (error) {
      // 详细的错误日志
      consoleLogger.error(`获取岗位选择框列表失败: ${error instanceof Error ? error.message : String(error)}`, {
        operator: req.user?.userName || 'unknown',
        stack: error instanceof Error ? error.stack : undefined
      });
      if (!res.headersSent) {
        ApiResponse.error(res, '获取岗位选择框列表失败');
      }
    }
  }
  
  /**
   * 获取岗位详细信息
   * @param req 请求对象
   * @param res 响应对象
   */
  async getInfo(req: AuthRequest, res: Response) {
    try {
      const postId = parseInt(req.params.postId);
      
      // 请求日志
      consoleLogger.info("获取岗位详细信息请求", {
        params: req.params,
        operator: req.user?.userName || 'unknown',
      });
      
      // 查询岗位信息
      const data = await postService.selectPostById(postId);
      if (!data) {
        consoleLogger.warn("获取岗位详细信息 - 岗位不存在", {
          postId,
          operator: req.user?.userName || 'unknown',
        });
        ApiResponse.error(res, '岗位不存在');
        return;
      }
      
      // 结果日志
      logger.info("获取岗位详细信息成功", {
        response: {
          postId,
          postName: data.postName
        },
        operator: req.user?.userName || 'unknown',
      });
      
      // 服务层已经处理了数据格式，直接返回
      ApiResponse.success(res, data);
    } catch (error) {
      // 详细的错误日志
      consoleLogger.error(`获取岗位详细信息失败: ${error instanceof Error ? error.message : String(error)}`, {
        requestData: {
          params: req.params,
        },
        operator: req.user?.userName || 'unknown',
        stack: error instanceof Error ? error.stack : undefined
      });
      if (!res.headersSent) {
        ApiResponse.error(res, '获取岗位详细信息失败');
      }
    }
  }
  
  /**
   * 新增岗位
   */
  @RepeatSubmit({ expireSeconds: 5 })
  @Log({ title: '岗位管理', businessType: BusinessType.INSERT })
  async add(req: AuthRequest, res: Response) {
    try {
      const post = req.body;
      
      // 请求日志
      consoleLogger.info("新增岗位请求", {
        body: req.body,
        operator: req.user?.userName || 'unknown',
      });
      
      // 设置创建者
      post.createBy = req.user?.userName;
      
      // 新增岗位
      const result = await postService.insertPost(post);
      
      // 结果日志
      logger.info("新增岗位成功", {
        response: {
          postId: result.postId,
          postName: result.postName
        },
        operator: req.user?.userName || 'unknown',
      });
      
      ApiResponse.success(res, result);
    } catch (error) {
      // 详细的错误日志
      consoleLogger.error(`新增岗位失败: ${error instanceof Error ? error.message : String(error)}`, {
        requestData: {
          body: req.body,
        },
        operator: req.user?.userName || 'unknown',
        stack: error instanceof Error ? error.stack : undefined
      });
      if (!res.headersSent) {
        ApiResponse.error(res, '新增岗位失败');
      }
    }
  }
  
  /**
   * 修改岗位
   */
  @RepeatSubmit({ expireSeconds: 5 })
  @Log({ title: '岗位管理', businessType: BusinessType.UPDATE })
  async update(req: AuthRequest, res: Response) {
    try {
      const post = req.body;
      
      // 请求日志
      consoleLogger.info("修改岗位请求", {
        body: req.body,
        operator: req.user?.userName || 'unknown',
      });
      
      // 设置更新者
      post.updateBy = req.user?.userName;
      
      // 修改岗位
      const result = await postService.updatePost(post);
      
      // 结果日志
      logger.info("修改岗位成功", {
        response: {
          postId: post.postId,
          postName: post.postName
        },
        operator: req.user?.userName || 'unknown',
      });
      
      ApiResponse.success(res, result);
    } catch (error) {
      // 详细的错误日志
      consoleLogger.error(`修改岗位失败: ${error instanceof Error ? error.message : String(error)}`, {
        requestData: {
          body: req.body,
        },
        operator: req.user?.userName || 'unknown',
        stack: error instanceof Error ? error.stack : undefined
      });
      if (!res.headersSent) {
        ApiResponse.error(res, '修改岗位失败');
      }
    }
  }
  
  /**
   * 删除岗位
   */
  @RepeatSubmit({ expireSeconds: 5 })
  @Log({ title: '岗位管理', businessType: BusinessType.DELETE })
  async remove(req: AuthRequest, res: Response) {
    try {
      const postIds = req.params.postIds.split(',').map((id: string) => parseInt(id));
      
      // 请求日志
      consoleLogger.info("删除岗位请求", {
        params: req.params,
        postIds,
        operator: req.user?.userName || 'unknown',
      });
      
      // 删除岗位
      const result = await postService.deletePostByIds(postIds);
      
      // 结果日志
      logger.info("删除岗位成功", {
        response: {
          postIds,
          result
        },
        operator: req.user?.userName || 'unknown',
      });
      
      ApiResponse.success(res, result);
    } catch (error) {
      // 详细的错误日志
      consoleLogger.error(`删除岗位失败: ${error instanceof Error ? error.message : String(error)}`, {
        requestData: {
          params: req.params,
        },
        operator: req.user?.userName || 'unknown',
        stack: error instanceof Error ? error.stack : undefined
      });
      if (!res.headersSent) {
        ApiResponse.error(res, '删除岗位失败');
      }
    }
  }
}

export default new PostController(); 